<template>
    <rx-dialog @handOk="handleSubmit" :oktext="$ti18('rxForm.commitBtn','提交')" :canceltext="$ti18('rxForm.closeBtn','关闭')" @cancel="cancel" btnalign="right" order="top">
        <rx-layout>
            <div slot="left" style="width:220px" showButton="true">
                <div style="margin-left: 25px;margin-top: 10px">{{i18n('form.dataSouce','数据源')}}</div>
                <a-tree checkable :tree-data="instDatasource" @check="handleCheck" @select="handleSelect"></a-tree>
            </div>
            <div slot="center" class="form-atabs">
                <div style="color: red;margin-left: 20px;margin-top: 10px"><i style="margin-right:5px" class="iconfont iconicon-test33"></i>{{i18n('msa.reminder','温馨提醒：同步表单前请提前备份好当前机构的表单数据库!')}}</div>
                <a-tabs style="height: calc(100% - 80px);overflow: hidden" default-active-key="1" v-model="curTab" @tabClick="tabClick">
                    <a-tab-pane key="1" :tab="i18n('form.toBeExecuted','待执行')">
                        <a-collapse class="form-acollapse" v-if="formChangeLogList1.length>0" v-model:activeKey="activeKey">
                            <a-collapse-panel v-for="(formChangeLog,index) in formChangeLogList1"
                                              :key="formChangeLog.boAlias" :header="formChangeLog.boName">
                                <rx-grid
                                    :ref="formChangeLog.boAlias+'_sql1'"
                                    :dataSource="formChangeLog.sqlList"
                                    :allowRowSelect="true"
                                    :multiSelect="true"
                                    :showPage="false"
                                    :bordered="true"
                                    :columns="columns"
                                    id-field="id"
                                    style="height: 300px;"
                                >
                                    <span slot="type" slot-scope="{ text, record }">
                                          <a-tag :color="typeMap[text].color">
                                            <span>{{ typeMap[text].text }}</span>
                                          </a-tag>
                                    </span>
                                    <span slot="action" slot-scope="{ text, record }" class="actionIcons">
                                       <span @click.stop="copySql(record.sql)">{{i18n('form.copySql','复制SQL')}}</span>
                                       <span @click.stop="setIgnore(record,true)">{{i18n('form.ignore','忽略')}}</span>
                                    </span>
                                </rx-grid>
                            </a-collapse-panel>
                        </a-collapse>
                        <div v-else>
                            <div v-for="(img,index) of image" :key="index" v-if="index==curDsAliasindex">
                                    <img  class="form-chang-img" :src="img.image" />
                                    <div style="text-align: center;margin-top: 15px">{{img.name}}</div>
                            </div>
                        </div>
                    </a-tab-pane>
                    <a-tab-pane key="2" :tab="i18n('form.executed','已执行')">
                        <a-collapse class="form-acollapse" v-model:activeKey="activeKey" v-if="formChangeLogList2.length>0">
                            <a-collapse-panel v-for="(formChangeLog,index) in formChangeLogList2"
                                              :key="formChangeLog.boAlias" :header="formChangeLog.boName">
                                <rx-grid
                                    :ref="formChangeLog.boAlias+'_sql2'"
                                    :dataSource="formChangeLog.sqlList"
                                    :allowRowSelect="false"
                                    :showPage="false"
                                    :bordered="true"
                                    :columns="columns2"
                                    id-field="id"
                                    style="height: 300px;"
                                >
                                    <span slot="status" slot-scope="{ text, record }">
                                          <a-tag :color="statusMap[text].color">
                                            <span>{{ statusMap[text].text }}</span>
                                          </a-tag>
                                    </span>
                                    <span slot="action" slot-scope="{ text, record }" class="actionIcons">
                                        <span @click.stop="copySql(record.sql)">{{i18n('form.copySql','复制SQL')}}</span>
                                    </span>
                                </rx-grid>
                            </a-collapse-panel>
                        </a-collapse>
                        <div v-else>
                            <div v-for="(img,index) of image" :key="index" v-if="index==curDsAliasindex">
                                <img  class="form-chang-img" :src="img.image" />
                                <div style="text-align: center;margin-top: 15px">{{img.name}}</div>
                            </div>
                        </div>
                    </a-tab-pane>
                    <a-tab-pane key="3" :tab="i18n('form.haveIgnored','已忽略')">
                        <a-collapse class="form-acollapse" v-model:activeKey="activeKey" v-if="formChangeLogList3.length>0">
                            <a-collapse-panel v-for="(formChangeLog,index) in formChangeLogList3"
                                              :key="formChangeLog.boAlias" :header="formChangeLog.boName">
                                <rx-grid
                                    :ref="formChangeLog.boAlias+'_sql3'"
                                    :dataSource="formChangeLog.sqlList"
                                    :allowRowSelect="false"
                                    :showPage="false"
                                    :bordered="true"
                                    :columns="columns"
                                    id-field="id"
                                    style="height: 300px;"
                                >
                                    <span slot="type" slot-scope="{ text, record }">
                                          <a-tag :color="typeMap[text].color">
                                            <span>{{ typeMap[text].text }}</span>
                                          </a-tag>
                                    </span>
                                    <span slot="action" slot-scope="{ text, record }" class="actionIcons">
                                        <span @click.stop="copySql(record.sql)">{{i18n('form.copySql','复制SQL')}}</span>
                                        <span @click.stop="setIgnore(record,false)">{{i18n('form.unignore','取消忽略')}}</span>
                                    </span>
                                </rx-grid>
                            </a-collapse-panel>
                        </a-collapse>
                        <div v-else>
                            <div v-for="(img,index) of image" :key="index" v-if="index==curDsAliasindex">
                                <img  class="form-chang-img" :src="img.image" />
                                <div style="text-align: center;margin-top: 15px">{{img.name}}</div>
                            </div>
                        </div>
                    </a-tab-pane>
                </a-tabs>
            </div>
        </rx-layout>
    </rx-dialog>
</template>

<script>
import FormChangeLogApi from '@/api/form/core/formChangeLog';
import {RxFit, RxGrid, Util} from "@lowcode/jpaas-common-lib";
import FormDataSourceDefApi from "@/api/form/core/formDataSourceDef";

export default {
    name: 'FormChangeLogs',
    props: {
        layerid: {
            type: String,
            default: ""
        },
        destroy: {
            type: Function
        },
        dsAlias: {
            type: String,
            default: ""
        }
    },
    components: {
        RxFit,
        RxGrid
    },
    data() {
        return {
            image:[
                {
                    image:require('@/image/selectDataSouce.png'),
                    name:this.i18n('msa.selDatesource','请从右边选择数据源'),
                },
                {
                    image:require('@/image/noData.png'),
                    name:this.i18n('msa.noData','暂无数据'),
                },
            ],
            columns: [
                {
                    title: this.$ti18('rxList.index','序号'),
                    type: 'indexColumn',
                    width: "5%",
                    dataIndex: 'serial',
                    scopedSlots: {customRender: 'serial'}
                },
                {title: this.i18n('form.boAlias','实体别名'), dataIndex: 'boAlias', width: "10%"},
                {title: this.i18n('form.type','类型'), dataIndex: 'type', width: "5%", scopedSlots: {customRender: 'type'}},
                {title: this.i18n('form.updateTime','变更时间'), dataIndex: 'createTime', width: "15%"},
                {title: this.i18n('form.sql','SQL语句'), dataIndex: 'sql', width: "55%"},
                {title: this.$ti18('rxList.action','操作'), width: "10%", dataIndex: 'action', scopedSlots: {customRender: 'action'}}
            ],
            columns2: [
                {title: this.$ti18('rxList.index','序号'), type: 'indexColumn', width: "5%", dataIndex: 'serial', scopedSlots: {customRender: 'serial'}},
                {title: this.i18n('form.noData','数据源别名'), dataIndex: 'datasource', width: "10%"},
                {title: this.i18n('form.executor','执行人'), dataIndex: 'createByName', width: "10%"},
                {title: this.i18n('form.exeTime','执行时间'), dataIndex: 'createTime', width: "15%"},
                {title: this.i18n('form.type','类型'), dataIndex: 'status', width: "5%", scopedSlots: {customRender: 'status'}},
                {title: this.i18n('form.sql','SQL语句'), dataIndex: 'sql', width: "45%"},
                {title: this.$ti18('rxList.action','操作'), width: "10%", dataIndex: 'action', scopedSlots: {customRender: 'action'}}
            ],
            statusMap: {
                '1': {color: 'green', text: this.i18n('statusMap.success','成功')},
                '0': {color: 'red', text: this.i18n('statusMap.failure','失败')},
            },
            curTab:"1",
            activeKey: [],
            //待执行
            formChangeLogList1: [],
            //已执行
            formChangeLogList2: [],
            //忽略
            formChangeLogList3: [],
            params: {
                boAlias: "",
                type: ""
            },
            typeMap: {
                'add': {color: 'green', text: this.$ti18('rxList.add','新增')},
                'upd': {color: 'blue', text: this.$ti18('rxList.update','更新')},
                'del': {color: 'red', text: this.$ti18('rxList.delBtn','删除')}
            },
            //数据源
            instDatasource: [],
            //选择的数据源
            selectDatasource: [],
            curDsAlias: "",
            curDsAliasindex:0,
            /*
            * 需要提交的数据
            * {
            *   boAlias:[selectedRowKeys]
            * }
            * */
            submitData:{}
        }
    },
    created() {
        //获取租户使用的数据源
        this.getInstDatasource();
    },
    methods: {
        i18n(name,text,key){
            return this.$ti18(name,text,"FormChangeLog",key);
        },
        handleSubmit(vm) {
            var self = this;
            if(this.selectDatasource && this.selectDatasource.length ==0){
                this.$message.warning(self.i18n('msa.selOneDatesource','至少选择一个数据源!'));
                vm.loading = false;
                return;
            }
            var submitData=this.getSubmitData();
            //验证选择的数据源是否选择了需要执行的sql
            let keys = Object.keys(submitData);
            for (let i = 0; i < keys.length; i++) {
                if(!submitData[keys[i]] || submitData[keys[i]].length==0){
                    this.$message.warning(keys[i]+self.i18n('msa.noSelSql','未选择需要执行的sql!'));
                    vm.loading = false;
                    return;
                }
            }
            this.$confirm({
                title: self.i18n('msa.syncTips','你确定要同步选中的记录吗？'),
                content: self.i18n('msa.syncBackTips','同步前请先备份数据库！'),
                okText: self.$ti18('rxForm.ackBtn','确认'),
                cancelText: self.$ti18('rxForm.cancelBtn','取消'),
                keyboard: true,
                zIndex: 999999,
                onOk() {
                    FormChangeLogApi.syncForm(submitData).then(res=>{
                        vm.loading = false;
                        self.curTab="1";
                        self.getFormChangeLogList(self.curDsAlias);
                        this.formChangeLogList2=[];
                        this.formChangeLogList3=[];
                    });
                },
                onCancel() {
                    vm.loading = false;
                },
            });

        },
        cancel() {
            Util.closeWindow(this, "cancel")
        },
        getFormChangeLogList(dsAlias) {
            if (dsAlias) {
                FormChangeLogApi.getFormChangeLog({
                    dsAlias: dsAlias,
                    params: JSON.stringify(this.params)
                }).then(res => {
                    if (res && res.success) {
                        this.formChangeLogList1 = this.buildData(res.data);
                    }
                });
            }
        },
        //获取租户使用的数据源
        getInstDatasource() {
            FormDataSourceDefApi.getInstDatasource().then(res => {
                if (res && res.success) {
                    for (let i = 0; i < res.data.length; i++) {
                        this.instDatasource.push({
                            title: res.data[i].name,
                            key: res.data[i].alias
                        });
                    }
                }
            });
        },
        handleSelect(values) {
            if(this.curDsAlias!=values[0]){
                this.curTab="1";
                this.formChangeLogList2=[];
                this.formChangeLogList3=[];
                this.getFormChangeLogList(values[0]);
                if(this.curDsAlias){
                    var selectedRowKeys = this.getSelectedRowKeys();
                    //将选好的数据存入提交数据中
                    this.submitData[this.curDsAlias]=selectedRowKeys;
                }
                this.curDsAlias = values[0];
            }
        },
        handleCheck(values, e) {
            if(e.checked && this.curDsAlias!=e.node.dataRef.key){
                this.getFormChangeLogList(e.node.dataRef.key);
                this.curDsAlias=e.node.dataRef.key;
            }
            this.selectDatasource=[];
            for (let i = 0; i < values.length; i++) {
                this.selectDatasource.push(values[i]);
            }
        },
        tabClick(tab) {
            //已执行
            if(tab=='2'){
                //防止多次点击调用后端
                if(this.formChangeLogList2.length==0){
                    FormChangeLogApi.getExecutedLog(this.curDsAlias).then(res=>{
                        if (res && res.success && res.data) {
                            this.formChangeLogList2 = this.buildData(res.data);
                        }
                    });
                }
            }else if(tab=='3'){
                if(this.formChangeLogList3.length==0){
                    this.getIgnoreFormChangeLog();
                }
            }
        },
        getIgnoreFormChangeLog(){
            FormChangeLogApi.getIgnoreFormChangeLog(this.curDsAlias).then(res=>{
                if (res && res.success && res.data) {
                    this.formChangeLogList3 = this.buildData(res.data);
                }
            });
        },
        setIgnore(record, ignore) {
            var self=this;
            this.$confirm({
                title: self.$ti18('rxMsa.actionTips','操作提示'),
                content: ignore?self.i18n('msa.ignoreTips','你确定要忽略选中的记录吗?'):self.i18n('msa.unignoreTips','你确定要取消忽略选中的记录吗?'),
                okText: self.$ti18('rxForm.ackBtn','确认'),
                cancelText: self.$ti18('rxForm.cancelBtn','取消'),
                keyboard: true,
                zIndex: 999999,
                onOk: function () {
                    FormChangeLogApi.setIgnore({
                        dsAlias:self.curDsAlias,
                        changeLogId:record.id,
                        ignore:ignore
                    }).then(res=>{
                        if(res && res.success){
                            self.getFormChangeLogList(self.curDsAlias);
                            if(!ignore){
                                self.getIgnoreFormChangeLog();
                            }
                        }
                    });
                },
                onCancel() {
                },
            });
        },
        /*
        * 构建数据
        * newData :[
        * {boAlias:boAlias,boName:boName,sqlList:[]}
        * ]
        * */
        buildData(ary) {
            var newData = [];
            for (let i = 0; i < ary.length; i++) {
                let data = ary[i];
                if (newData.length > 0) {
                    var obj = newData.find(item => item.boAlias == data.boAlias);
                    if (obj) {
                        obj.sqlList.push(data);
                    } else {
                        this.activeKey.push(data.boAlias);
                        newData.push({
                            boAlias: data.boAlias,
                            boName: data.boName,
                            sqlList: [data]
                        })
                    }
                } else {
                    this.activeKey.push(data.boAlias);
                    newData.push({
                        boAlias: data.boAlias,
                        boName: data.boName,
                        sqlList: [data]
                    })
                }
            }
            return newData;
        },
        copySql(sql) {
            let tag = document.createElement('input');
            tag.setAttribute('id', 'copyInput');
            tag.value = sql;
            document.getElementsByTagName('body')[0].appendChild(tag);
            document.getElementById('copyInput').select();
            document.execCommand('copy');
            document.getElementById('copyInput').remove();
            this.$message.success("复制成功!");
        },
        //获取选中的数据
        getSelectedRowKeys(){
            var selectedRowKeys=[];
            for (let i = 0; i < this.formChangeLogList1.length; i++) {
                selectedRowKeys.push(...this.$refs[this.formChangeLogList1[i].boAlias+"_sql1"][0].selectedRowKeys);
            }
            return selectedRowKeys;
        },
        //获取当前选中的数据源的提交数据
        getSubmitData(){
            var submitData={};
            for (let i = 0; i < this.selectDatasource.length; i++) {
                var dsAlias=this.selectDatasource[i];
                //为当前选中的数据源
                if(this.curDsAlias==dsAlias){
                    var selectedRowKeys = this.getSelectedRowKeys();
                    submitData[dsAlias]=selectedRowKeys;
                }else {
                    submitData[dsAlias]=this.submitData[dsAlias];
                }
            }
            return submitData;
        }
    },
    watch:{
        curDsAlias(o,_o){
            if(!o){
                this.curDsAliasindex = 0;
            }else{
                this.curDsAliasindex = 1;
            }

        }
    }
}
</script>
<style scoped>
.form-atabs >>> .ant-collapse > .ant-collapse-item:last-child{
    border-bottom: none!important;
}
.form-acollapse{
    width: calc(100% - 20px);
    margin-left: 10px;
    max-height: calc(100% - 60px);
    overflow: auto;
    border-bottom: 1px solid #d9d9d9;
}
.form-chang-img{
    margin-top:200px;
    margin-left: calc(50% - 110px);
}
</style>

